﻿using Anka2.Views;
using edem2simpack.Models;
using edem2simpack.Views;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using static System.Net.Mime.MediaTypeNames;

namespace edem2simpack.ViewModels
{
    public class MainWindowViewModel : NotifyObject
    {
        private Window RootSource { set; get; }       
       

        CosimulationViewModel? CosimulationContext;

        private CommandObject<RoutedEventArgs> _new_Executed;
        public CommandObject<RoutedEventArgs> New_Executed
        {
            get
            {
                if (_new_Executed == null)
                    _new_Executed = new CommandObject<RoutedEventArgs>(
                        new Action<RoutedEventArgs>(e =>
                        {
                            RootSource = DataUitls.GetParentWindow((DependencyObject)e.Source);                            
                            if(CosimulationContext is not null)
                            {
                                CosimulationContext = null;
                            }
                            CosimulationContext = ((MainWindow)RootSource).CosimulationSheet.DataContext as CosimulationViewModel;
                            CosimulationContext.SpckFile = null;
                            CosimulationContext.FmuFile = null;
                            Info = null;


                        }));
                return _new_Executed;
            }
        }

        private string _info;
        public string Info
        {
            get => _info;
            set
            {
                if (_info != value)
                {
                    _info = value;
                }
                RaisePropertyChanged(nameof(Info));
            }
        }
        private string fmuFile;
        private string spckFile;
       

        private CommandObject<RoutedEventArgs> _run_Executed;
        public CommandObject<RoutedEventArgs> Run_Executed
        {
            get
            {
                if (_run_Executed == null)
                    _run_Executed =  new  CommandObject<RoutedEventArgs>(
                        new   Action<RoutedEventArgs>(async e =>
                        {
                            RootSource = DataUitls.GetParentWindow((DependencyObject)e.Source);                            
                            if (CosimulationContext is not null)
                            {
                                CosimulationContext = null;
                            }
                            CosimulationContext = ((MainWindow)RootSource).CosimulationSheet.DataContext as CosimulationViewModel;
                            spckFile = CosimulationContext.SpckFile;
                            fmuFile = CosimulationContext.FmuFile;
                            if(!string.IsNullOrEmpty(spckFile)&& !string.IsNullOrEmpty(fmuFile))
                            {
                                string exePath = "fmiMain.exe ";
                                string parameters = " fmu=" + fmuFile + " spck=" + spckFile;                               
                                exec(exePath, parameters);                                
                            }
                        }));
                return _run_Executed;
            }
        }

        private void exec(string exePath,string parameters)
        {
            Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = exePath;
            process.StartInfo.Arguments = parameters;
            process.StartInfo.UseShellExecute= false;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput= true;
            process.Start();
            process.BeginOutputReadLine();
            process.OutputDataReceived += new DataReceivedEventHandler(processOutputDataReceived);
        }

        string sbrSourceFile = null;
        private void processOutputDataReceived(object sender, DataReceivedEventArgs e)
        {
           
            if (e.Data != null)
            {
                string eData = e.Data;
                if (e.Data.Contains(".sbr"))
                {
                    sbrSourceFile = eData.Split('"')[1];
                    eData = "Creating sbr file...";
                }
                   
                if (eData.Contains("successfully finished"))
                {
                    string resultPath = null;
                    if (spckFile is not null)
                    {
                        string[] spckPathList = spckFile.Split('\\', StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 0; i < spckPathList.Length - 1; i++)
                        {
                            resultPath = resultPath + spckPathList[i] + "\\";
                        }
                        resultPath = resultPath + "output";
                    }
                    if (!Directory.Exists(resultPath))
                    {
                        Directory.CreateDirectory(resultPath);
                    }
                    FileInfo file = new FileInfo(sbrSourceFile);
                    string resultfile = Path.Combine(resultPath, file.Name);
                    if (file.Exists)
                    {
                        file.CopyTo(resultfile, true);
                    }
                    Info = Info + "created file \"" + resultfile + "\".\n";
                }
                Info = Info + eData + "\n";               
            }

           
            //MessageBox.Show(e.Data);
        }
                
        private CommandObject<RoutedEventArgs> _help_Executed;
        public CommandObject<RoutedEventArgs> Help_Executed
        {
            get
            {
                if (_help_Executed == null)
                    _help_Executed = new CommandObject<RoutedEventArgs>(
                        new Action<RoutedEventArgs>(e =>
                        {
                            string filepath = AppDomain.CurrentDomain.BaseDirectory + @"Doc\UserGuide.pdf";
                            try
                            {
                                ProcessStartInfo processStartInfo = new ProcessStartInfo(filepath);
                                Process process = new Process();
                                process.StartInfo = processStartInfo;
                                process.StartInfo.UseShellExecute = true;
                                process.Start();
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("找不到帮助文件!");
                            }

                        }));
                return _help_Executed;
            }
        }

        

        private CommandObject<RoutedEventArgs> _about_Executed;
        public CommandObject<RoutedEventArgs> About_Executed
        {
            get
            {
                if (_about_Executed == null)
                    _about_Executed = new CommandObject<RoutedEventArgs>(
                        new Action<RoutedEventArgs>(e =>
                        {
                            RootSource = DataUitls.GetParentWindow((DependencyObject)e.Source);
                            About about = new About();
                            about.ShowDialog();
                        }));
                return _about_Executed;
            }
        }
    }
}
